/**
 * @authors tanqichao
 * @date    2017-03-21 13:59:27
 * @module  广告计划创建&编辑
 */

import { Row, Col, Form, Input, Radio, Button, DatePicker, Checkbox, Table, message, Icon, Modal, Switch } from 'antd';
import React, { Component, PropTypes } from 'react';
import Styles from './createPlan/index.less';
import RegionModal from './item/regionModal';
import PacketModal from './item/packetModal';
import TimePeriod from './item/TimePeriod';
import Industry from './item/industry';
import Region from './item/Region';
import Media from './item/Media';
import Scene from './item/Scene';
import Crowd from './item/Crowd';
import { AccessControl } from '../../utils/common';
import moment from 'moment';;

const CheckboxGroup = Checkbox.Group;
const { RangePicker } = DatePicker;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {span: 2},
  wrapperCol: {span: 11}
};

class Detail extends Component {
	constructor(props) {
		super(props);
		this.state = {
			endTime: '',
			beginTime: '',
			industryIds: [],
      packetVisible: false,
      selectList: [],
      type: ''
		}
	}
	submit = (type) => {
    const permissionList = this.props.permissions;

		this.props.form.validateFields((error, values) => {
			const state = this.state;
			let dispatchType = '',
					params = null;
			if (error) return ;
			if (!this.props.regionCodes) {
				message.error('请选择投放区域', 3);
				return;
			}
			if (!this.props.industryIds.length) {
				message.error('请选择标签', 3);
				return;
			}
      if (!this.props.crGrpIds.length) {
				message.error('请添加创意包', 3);
				return;
			}

			if (type === 'submit') {
				dispatchType = 'createPlan/submit';
				params = Object.assign(values, {
					endTime: state.endTime,
					beginTime: state.beginTime,
          regionCodes: this.props.regionCodes.split(','),
					industryIds: this.props.industryIds,
          crGrpIds: this.props.crGrpIds,
          periodList: [],
          mediaCodes: this.props.mediaCodes,
          sceneCodes: this.props.sceneCodes,
          crowdCodes: this.props.crowdCodes
				});
			}

			if (type === 'modify') {
				dispatchType = 'createPlan/modify';
				params = Object.assign(values, {
					id: this.props.id,
					endTime: state.endTime || this.props.endTime,
					beginTime: state.beginTime || this.props.beginTime,
          regionCodes: this.props.regionCodes.split(','),
					industryIds: this.props.industryIds,
          crGrpIds: this.props.crGrpIds,
          periodList: [],
          mediaCodes: this.props.mediaCodes,
          sceneCodes: this.props.sceneCodes,
          crowdCodes: this.props.crowdCodes
				});
			}

      if (AccessControl(permissionList, 'dsp_agent_admin')) {
        params.appPids = values.appPids && values.appPids.length !== 0 ? values.appPids.split(',') : []
      } else {
        params.appPids = (this.props.appPids && this.props.appPids.length > 0) ?  this.props.appPids.join(',').split(',') : []
      }

			this.props.dispatch({
        type: 'createPlan/setLoading',
        payload: {
          createLoading: true
        }
      });

			this.props.dispatch({
				type: dispatchType,
				payload: JSON.stringify(
          params
        )
			})

		})
	}

	// 广告出价
	validateFee = (rule, value, callback) => {
		if (value && Number(value) < 0.4) {
			callback('不小于0.4的数字，保留小数点后2位')
		}
		callback()
	}

	// 每日预算
	validateDayBudget = (rule, value, callback) => {
		if (value && Number(value) < 100) {
			callback('不能低于100')
		}
		callback()
	}

  // 投放日期
	setEffectDaterange = (value, dateString) => {
		this.setState({
			beginTime: dateString[0],
			endTime: dateString[1]
		})
	}

	// 投放区域选择文案
	renderRegionTitle = () => {
		if (!this.props.regionCodes.length) {
			return '未选择';
		}
		const regionCodes = this.props.regionCodes.split(',');
    if (regionCodes.includes('10') && regionCodes.includes ('999')) {
      return '全部地域';
    }
    return '部分地域';
	}

	// 投放区域
	setRegion = (values) => {
		this.props.dispatch({
			type: "createPlan/setRegion",
			payload: { regionCodes: values }
		});
		this.renderRegionTitle();
	}

	// 行业标签
	setIndustryIds = (industryIds) => {
		this.props.dispatch({
      type: 'createPlan/setIndustryIds',
      payload: { industryIds: industryIds }
    })
	}

  // 保存创意包
  setPacket = () => {
    const { creativeGroupVOs, packetList, crGrpIds } = this.props
    const group = []
    // console.log(creativeGroupVOs)
    // console.log(crGrpIds)

    packetList && packetList.map((list) => {
      crGrpIds.map((item) => {
        if (item === list.id) {
          group.push(list)
        }
      })
    })
    // console.log(group)
    this.props.dispatch({
      type: 'createPlan/setCreativeGroupVOs',
      payload: {
        creativeGroupVOs: group
      }
    })
  }

  // 删除创意包
  delete = (id) => {
    const {creativeGroupVOs, crGrpIds} = this.props;
    const list = [].concat(creativeGroupVOs)
    const ids = [].concat(crGrpIds)

    list && list.map((item, index) => {
      if (item.id === id) {
        list.splice(index, 1)
        ids.splice(index, 1)
      }
    })

    this.props.dispatch({
      type: 'createPlan/setCreativeGroupVOs',
      payload: {
        creativeGroupVOs: list
      }
    })

    this.setCrGrpIds(ids)
  }

  setCrGrpIds = (crGrpIds) => {
    this.props.dispatch({
      type: 'createPlan/setCrGrpIds',
      payload: {
        crGrpIds: crGrpIds
      }
    })
  }

  // 搜索
  search = (keyWord) => {
    this.props.dispatch({
      type: 'createPlan/queryPacket',
      payload: JSON.stringify({
        "type": this.state.type,
        "title": keyWord
      })
    })
  }

  // 请求创意包
  fetchPacket = (type) => {
    this.props.dispatch({
      type: 'createPlan/queryPacket',
      payload: JSON.stringify({
        type: type
      })
    })
  }

  renderPacketList = () => {
    const content = [];
    const { creativeGroupVOs } = this.props;

    creativeGroupVOs && creativeGroupVOs.length > 0 &&  creativeGroupVOs.map((item) => {
      content.push(
        <li className={Styles.item} key={item.id}>
          <div className={Styles.packetTitle}>
            <p className={Styles.imgName}>{item.title}</p>
            <p className={Styles.packetId}>创意包ID：{item.id}</p>
          </div>
          <div className={Styles.packetDel}>
            <p><Icon type="close-circle" className={Styles.itemIcon} onClick={this.delete.bind(this, item.id)} /></p>
          </div>
          <img className={Styles.previewImg} src={item.imgUrls[0]} />
        </li>
      )
    })
    return (
      <ul className={Styles.packetList}>{content}</ul>
    )
  }

  renderPacket = () => {
    return (
      <FormItem
        label="创意包"
        required
        {...formItemLayout}
      >
        <div className={Styles.packet}>
          <div className={Styles.content}>
            {this.props.crGrpIds && this.props.crGrpIds.length > 0 && this.renderPacketList()}
            <div className={Styles.uploadMaterial}>
              <PacketModal
                {...this.props}
                search={this.search}
                fetchPacket={this.fetchPacket}
                type={this.props.type || this.state.type}
                onComplete={this.setPacket}
                setCrGrpIds={this.setCrGrpIds}
              />
            </div>
          </div>
        </div>
      </FormItem>
    )
  }

  // 广告类型
  setAdType = (e) => {
    this.setState({
      type: e.target.value
    })

    this.props.dispatch({
      type: 'createPlan/setCreativeGroupVOs',
      payload: {
        creativeGroupVOs: []
      }
    })

    this.props.dispatch({
      type: 'createPlan/setCrGrpIds',
      payload: {
        crGrpIds: []
      }
    })
  }

  // 投放人群
  setCrowdCodes = (crowdCodes) => {
    console.log(crowdCodes)
    this.props.dispatch({
      type: 'createPlan/setCrowdCodes',
      payload: {
        crowdCodes: crowdCodes
      }
    })
  }

  // 投放场景
  setSceneCodes = (sceneCodes) => {
    console.log(sceneCodes)
    this.props.dispatch({
      type: 'createPlan/setSceneCodes',
      payload: {
        sceneCodes: sceneCodes
      }
    })
  }

  // 投放媒体
  handleMedia = (mediaCodes) => {
    console.log(mediaCodes)
    this.props.dispatch({
      type: 'createPlan/setMediaCodes',
      payload: {
        mediaCodes: mediaCodes
      }
    })
  }

  // 投放时间
  setPeriodList = (list) => {
    console.log(list)
    this.props.dispatch({
      type: 'createPlan/setPeriodList',
      payload: {
        periodList: list
      }
    })
  }

	createDom = () => {
		const { getFieldDecorator } = this.props.form;
    const { action, packetList, crGrpIds } = this.props;
    const permissionList = this.props.permissions;

		return (
			<Form>
				<div className={Styles.title}><em className={Styles.one}></em>基本信息</div>
				<FormItem
					label="推广名称"
					{...formItemLayout}
				>
	        {getFieldDecorator('name', {
	        	initialValue: action ? this.props.name : '',
	          rules: [{
	          	required: true,
	          	message: '请填写推广名称'
	          }]
	        })(
	          <Input placeholder="不超过20个字" maxLength={20} />
	        )}
	      </FormItem>
				<FormItem
					label="计费方式"
					{...formItemLayout}
				>
					{getFieldDecorator('chargeType', {
						initialValue: "1"
					})(
						<RadioGroup>
							<Radio value="1">CPC（按点击计费）</Radio>
						</RadioGroup>
	        )}
				</FormItem>
				<FormItem
					label="广告出价"
					{...formItemLayout}
				>
					{getFieldDecorator('fee', {
						initialValue: action ? this.props.fee : '',
						rules: [{
							required: true,
							message: '请填写广告出价'
						}, {
							validator: this.validateFee
						}]
					})(
						<Input placeholder="每一次有效点击的付费金额，填写不小于0.4" addonAfter="元" />
					)}
				</FormItem>
				<FormItem
					label="每日预算"
					{...formItemLayout}
				>
					{getFieldDecorator('dayBudget', {
						initialValue: action ? this.props.dayBudget : '',
						rules: [{
							required: true,
							message: '请填写每日预算'
						}, {
							validator: this.validateDayBudget
						}]
					})(
						<Input placeholder="每天的消费金额上限，不填则不限，填写则必须高于100" addonAfter="元" />
					)}
				</FormItem>
				<FormItem
					label="投放平台"
					{...formItemLayout}
				>
					{getFieldDecorator('platform', {
						initialValue: this.props.platform,
						rules: [{
							required: true,
							message: '至少选择一项'
						}]
					})(
            <RadioGroup>
              <Radio value={1}>全部</Radio>
              <Radio value={2}>Android</Radio>
              <Radio value={3}>IOS</Radio>
            </RadioGroup>
					)}
				</FormItem>
				<FormItem
					label="投放日期"
					{...formItemLayout}
				>
					{getFieldDecorator('effectDaterange', {
						initialValue: this.props.effectDaterange,
						rules: [{
							type: 'array',
							required: true,
							message: '请选择投放日期'
						}],
						onChange: this.setEffectDaterange
					})(
						<RangePicker />
					)}
				</FormItem>
	      <FormItem
	      	required
					label="标签"
					labelCol = {{ span: 4 }}
					wrapperCol = {{ span: 20}}
				>
	      	<Industry
	      		{...this.props}
	      		onComplete={this.setIndustryIds}
	      	/>
	      </FormItem>
        <div className={Styles.title}><em className={Styles.four}></em>高级设定</div>
        {
          //<FormItem
  	      // 	required
  				// 	label="时段设置"
  				// 	labelCol = {{ span: 4 }}
  				// 	wrapperCol = {{ span: 20}}
  				// >
          //   <TimePeriod
          //     {...this.props}
          //     onComplete={this.setPeriodList}
          //   />
  	      // </FormItem>
        }

        <FormItem
	      	required
					label="投放区域"
					{...formItemLayout}
				>
          <RegionModal
            {...this.props}
            onComplete={this.setRegion}
          />
				</FormItem>

        <FormItem
	      	required
					label="投放人群"
					labelCol = {{ span: 4 }}
					wrapperCol = {{ span: 20}}
				>
          <Crowd
            {...this.props}
            onComplete={this.setCrowdCodes}
          />
	      </FormItem>

        <FormItem
	      	required
					label="投放媒体"
					labelCol = {{ span: 4 }}
					wrapperCol = {{ span: 20}}
				>
          <Media {...this.props} onComplete={this.handleMedia} />
	      </FormItem>

        {
          AccessControl(permissionList, 'dsp_agent_admin') ?
          <FormItem
  	      	required
  					label="场景设置"
  					labelCol = {{ span: 4 }}
  					wrapperCol = {{ span: 20}}
  				>
            <Scene
              {...this.props}
              sceneComplete={this.setSceneCodes}
            />
  	      </FormItem> : null}

        {
          AccessControl(permissionList, 'dsp_agent_admin') ?
          <FormItem
  					label="投放广告位"
            {...formItemLayout}
  				>
            {getFieldDecorator('appPids', {
  						initialValue: this.props.appPids && this.props.appPids.join(',') || ''
  					})(
              <Input placeholder="请用英文逗号进行分隔，如 1,2,3" />
  					)}
  	      </FormItem> : null}

        <div className={Styles.title}><em className={Styles.four}></em>广告策略</div>

        <FormItem
					label="广告类型"
					{...formItemLayout}
				>
					{getFieldDecorator('type', {
						initialValue: this.props.type || '',
						rules: [{
							required: true,
							message: '请选择广告类型'
						}],
            onChange: this.setAdType
					})(
            <RadioGroup disabled={this.props.type ? true : false}>
              <Radio value={1}>互动广告</Radio>
              <Radio value={2}>展示广告</Radio>
            </RadioGroup>
					)}
				</FormItem>
        {this.renderPacket()}
	  		<Row>
	  			<Col span={24}>
	  				{
	  					this.props.action === 'edit' ? <Button type="primary" onClick={this.submit.bind(this, 'modify')} loading={this.props.createLoading} className={Styles.submitBtn}>确认修改</Button> :
	  						<Button type="primary" onClick={this.submit.bind(this, 'submit')} loading={this.props.createLoading} className={Styles.submitBtn}>提交审核</Button>
	  				}
	  			</Col>
	  		</Row>
			</Form>
		)
	}

	render () {
		return (
			<div>
				{ this.createDom() }
			</div>
		)
	}
};

export default Form.create()(Detail);
